import {Component, OnInit} from '@angular/core';
import * as moment from "moment";
import {FormBuilder, FormGroup} from "@angular/forms";
import {FetchService} from "../../../../core/net/fetch.service";
import {OneMapService} from "../../../one-map/one-map.service";
import {NzMessageService} from "ng-zorro-antd";
import { format, startOfMonth, endOfMonth, subMonths, subDays } from 'date-fns';
import { UtilService } from '../../../../core/util/util.service';

@Component({
    selector: 'app-agri-drainage',
    templateUrl: './agri-drainage.component.html',
    styleUrls: ['./agri-drainage.component.scss', '../agriculture.component.scss']
})
export class AgriDrainageComponent implements OnInit {
    radioValue = 'single';
    listData = [];
    defaultKeys = [];
    stadiaCode: string; //  当前测站编码
    stationName: string;
    topDateModal = [startOfMonth(subMonths(new Date(), 1)), subDays(new Date(), 1)];    //  顶部日期选择 默认上月至今
    topDateRanges = {
        '昨日': [
            moment().subtract(1, 'days').valueOf(),
            moment().subtract(1, 'days').valueOf()
        ],
        '3日': [
            moment().subtract(3, 'days').valueOf(),
            new Date()
        ],
        '7日': [
            moment().subtract(7, 'days').valueOf(),
            new Date()
        ],
        '本月': [
            moment().startOf('month').valueOf(),
            new Date()
        ],
        '上月': [
            moment().subtract(1, 'months').startOf('month').valueOf(),
            moment().subtract(1, 'months').endOf('month').valueOf()
        ],
        '近3月': [
            moment().subtract(3, 'months').startOf('month').valueOf(),
            new Date()
        ],
    };
    processOpt: any = {
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "cross",
                animation: false,
                label: {
                    backgroundColor: "#505765"
                }
            }
        },
        legend: {
            data: ["水位", "流量"],
            bottom: 10
        },
        xAxis: {
            type: "category",
            data: []
        },
        yAxis: [
            // {
            //     name: "水位(m)",
            //     type: "value"
            // },
            {
                name: "流量(m³/s)",
                type: "value"
            }
        ],
        series: [
            // {
            //     name: "水位",
            //     type: "line",
            //     smooth: true,
            //     data: []
            // },
            {
                name: "流量",
                type: "line",
                yAxisIndex: 1,
                smooth: true,
                data: []
            }
        ]
    };
    processOptChange: any = {};
    processEchartsIntance: any;
    waterLevelDateModal = [startOfMonth(subMonths(new Date(), 1)), subDays(new Date(), 1)];    //  顶部日期选择 默认上月至今
    featureForm: FormGroup;

    /*****************  旬月特征值对比  *********************/
    monthForm: FormGroup;
    startValue: Date | null = null;
    endValue: Date | null = null;
    endOpen = false;
    monthData: any = {};
    monthOpt: any = {
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow"
            }
        },
        legend: {
            data: [],
            bottom: 0
        },
        grid: {
            top: "10%",
            bottom: "8%",
            left: "6%",
            right: "4%",
            containLabel: true
        },
        xAxis: {
            type: "category",
            data: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
        },
        yAxis: {
            type: "value"
        },
        series: []
    };
    monthOptChange: any = {};
    flowTotal = 0;
    /******************* end *******************/

    /******************* 监测数据 *******************/
    tableData = [];
    pageNum = 1;
    pageSize = 25;
    /******************* end *******************/


    /******************* 历史同期对比 *******************/
    historyForm: FormGroup;
    historyYearList = [];
    startHistoryValue: Date | null = null;
    endHistoryValue: Date | null = null;
    endHistoryOpen = false;
    historyOpt: any = {
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow"
            }
        },
        legend: {
            data: []
        },
        xAxis: {
            type: "category",
            data: []
        },
        yAxis: {
            type: "value"
        },
        series: [
            {
                type: "line",
                data: []
            }
        ]
    };
    historyOptChange: any = {};

    /******************* end *******************/
    constructor(private fetchService: FetchService,
                private mapService: OneMapService,
                private message: NzMessageService,
                private util: UtilService,
                private fb: FormBuilder) {
        this.featureForm = this.fb.group({
            alertVal: [''],
            limitVal: [''],
            maxVal: [''],
            minVal: [''],
            maxTime: [''],
            minTime: [''],
            avgVal: [''],
            medianVal: [''],
            last3AvgVal: [''],
            last3MedianVal: [''],
            last3MedianPer: [''],
            last3AvgPer: [''],
        });
        this.monthForm = this.fb.group({
            valType: ['1'],
            dateType: ['1'],
            startYear: [moment().subtract(10, 'year').valueOf()],
            endYear: [new Date()],
            currYear: [moment().year()]
        });
        this.historyYearList = this.getLastSeveralYears();
        this.historyForm = this.fb.group({
            yearStr: [[moment().year()]],
            startDateStr: [moment().subtract(1, 'month').valueOf()],
            endDateStr: [new Date()],
        });
    }

    ngOnInit() {
        this.fetchService.get<any>('report/drainage/listAllSite', {}).subscribe(res => {
            // console.log(res);
            this.listData = res;
            this.defaultKeys = [this.listData[0].children[0].key];
            this.stadiaCode = this.defaultKeys[0];
            this.stationName = this.listData[0].children[0].title;
            this.queryInfo();
        });
    }

    disabledStartDate = (startValue: Date): boolean => {
        if (!startValue || !this.endValue) {
            return false;
        }
        return startValue.getTime() > this.endValue.getTime();
    }

    disabledEndDate = (endValue: Date): boolean => {
        if (!endValue || !this.startValue) {
            return false;
        }
        return endValue.getTime() <= this.startValue.getTime();
    }

    onStartChange(date: Date): void {
        this.startValue = date;
    }

    onEndChange(date: Date): void {
        this.endValue = date;
    }

    handleStartOpenChange(open: boolean): void {
        if (!open) {
            this.endOpen = true;
        }
        // console.log('handleStartOpenChange', open, this.endOpen);
    }

    handleEndOpenChange(open: boolean): void {
        // console.log(open);
        this.endOpen = open;
    }

    /**********************  历史对比 ************************/
    disabledHistoryStartDate = (startValue: Date): boolean => {
        if (!startValue || !this.endHistoryValue) {
            return false;
        }
        return startValue.getTime() > this.endHistoryValue.getTime();
    }

    disabledHistoryEndDate = (endValue: Date): boolean => {
        if (!endValue || !this.startHistoryValue) {
            return false;
        }
        return endValue.getTime() <= this.startHistoryValue.getTime();
    }

    onStartHistoryChange(date: Date): void {
        this.startHistoryValue = date;
    }

    onEndHistoryChange(date: Date): void {
        this.endHistoryValue = date;
    }

    handleStartHistoryOpenChange(open: boolean): void {
        if (!open) {
            this.endHistoryOpen = true;
        }
    }

    handleEndHistoryOpenChange(open: boolean): void {
        this.endHistoryOpen = open;
    }

    /**********************************************/
    selectedAreaChanged(event): void {
        // console.log(event);
        const nodeClick = event.node;
        if (nodeClick.isLeaf) {
            this.stationName = event.selectedKeys[0].title;
            this.stadiaCode = event.selectedKeys[0].key;
            this.queryInfo();
        }
    }

    queryInfo(): void {
        // console.log(this.topDateModal);
        this.waterLevelDateModal = this.topDateModal;
        this.onQueryProcessList();
        this.onQueryMonthList();
        this.onQueryHistory();
    }

    private getItemValues(list, key) {
        return list.map(i => {
            return i[key] || 0;
        });
    }

    onQueryProcessList(): void {
        const params = {
            ditchId: this.stadiaCode,
            startDate: moment(this.waterLevelDateModal[0]).valueOf(),
            endDate: moment(this.waterLevelDateModal[1]).valueOf()
        };
        this.fetchService.post('report/drainage/data', params).subscribe(res => {
            if (res) {
                const list = res["data"];
                this.flowTotal = res['flowTotal'];
                res['minTime'] = moment(res['minTime']).format('YYYY-MM-DD HH:mm:ss');
                res['maxTime'] = moment(res['maxTime']).format('YYYY-MM-DD HH:mm:ss');
                this.featureForm.patchValue(res);
                this.processOptChange = {
                    legend: {
                        data: ["流量"],
                        bottom: 10
                    },
                    xAxis: {
                        data: list.map(o => {
                            return moment(o.meaTime).format('YYYY-MM-DD HH:mm:ss');
                        })
                    },
                    yAxis: [
                        {
                            name: "流量(m³/s)",
                            type: "value",
                            min: Math.floor(this.calcYAxisData('min', this.util.max(this.getItemValues(list, "flux")), this.util.min(this.getItemValues(list, "flux")))),
                            max: Math.ceil(this.calcYAxisData('max', this.util.max(this.getItemValues(list, "flux")), this.util.min(this.getItemValues(list, "flux")))),
                        }
                    ],
                    series: [
                        {
                            name: "流量",
                            type: 'line',
                            smooth: true,
                            markPoint: {
                                // symbol: 'diamond',
                                symbolSize: 30,
                                data: [
                                    {
                                        type: 'max',
                                        name: '最大'
                                    },
                                    {
                                        name: '最小',
                                        type: 'min'
                                    },
                                ],
                                label: {
                                    normal: {
                                        formatter: (p) => {
                                            // console.log(p);
                                            return `${p.name}: ${p.value}m³/s`;
                                        }
                                    }
                                }
                            },
                            data: this.getItemValues(list, "flux")
                        }
                    ]
                };
                list.forEach(item => {
                    item['date'] = moment(item['meaTime']).format('YYYY-MM-DD');
                    item['time'] = moment(item['meaTime']).format('HH:mm:ss');
                });
                this.tableData = list;
            }
        });
    }
    private calcYAxisData(type: string, max: number, min: number): number {
        if (type === 'max') {
            return max + (max - min) / 2;
        } else if (type === 'min') {
            return (min - (max - min)) >= 0 ? +(min - (max - min)) : 0;
        }
    }
    onQueryMonthList(): void {
        // console.log(this.monthForm.value);
        const params = {
            ditchId: this.stadiaCode,
            startYear: moment(this.monthForm.value.startYear).year(),
            endYear: moment(this.monthForm.value.endYear).year(),
            dateType: this.monthForm.value.dateType,
            valType: this.monthForm.value.valType
        };
        this.fetchService.post('report/drainage/monthXunCampare', params).subscribe(res => {
            if (res) {
                this.monthData = res;
                this.monthOptChange = {
                    legend: {
                        data: this.monthData.map(o => {
                            return o.year;
                        })
                    },
                    xAxis: {
                        data: this.monthData[0].data.map(o => {
                            return o.m;
                        })
                    },
                    series: this.monthData.map(o => {
                        return {
                            name: o.year,
                            type: "bar",
                            data: o.data.map(item => {
                                return item.flux;
                            })
                        };
                    })
                };
            }
        });
    }

    onQueryHistory(): void {
        console.log(this.historyForm.value);
        const params = {
            ditchId: this.stadiaCode,
            startDateStr: moment(this.historyForm.value.startDateStr).format('MM-DD'),
            endDateStr: moment(this.historyForm.value.endDateStr).format('MM-DD'),
            yearStr: this.historyForm.value.yearStr.join(',')
        };
        console.log(params);
        this.fetchService.post('report/drainage/historySameTimeCampare', params).subscribe(res => {
            if (res && Array.isArray(res)) {
                this.historyOptChange = {
                    legend: {
                        data: res.map(o => {
                            return o.year;
                        })
                    },
                    xAxis: {
                        data: res[0].data.map(o => {
                            return moment(o.meaTime).format("MM-DD HH:mm:ss");
                        })
                    },
                    series: res.map(o => {
                        return {
                            name: o.year,
                            type: "line",
                            // smooth: true,
                            data: o.data.map(item => {
                                return item.flux;
                            })
                        };
                    })
                };
            }
        });
    }

    private getLastSeveralYears(length = 10): Array<any> {
        const curYear = moment().year();
        const arr = [];
        for (let i = curYear - length; i <= curYear; i++) {
            arr.push(i);
        }
        return arr;
    }
}
